package method

import (
	"strings"

	"gitee.com/knowgo/gpa/engine/generator/defines"
	rdesc "gitee.com/knowgo/gpa/engine/generator/repo-desc"
	"gitee.com/knowgo/gpa/engine/generator/sqlgenerator"
)

type truncate struct {
	BaseMethod
}

func (g *truncate) Test(fn *defines.Func) bool {
	// 如果函数名称中有 By 字符串，则优先为 CountXBy 操作
	if strings.Index(fn.Name, "Truncate") == 0 {
		g.BaseMethod.Test(fn)
		fn.Template = defines.TRUNCATE
		return true
	}

	return false
}

func (g *truncate) Parse() (*rdesc.FuncDesc, error) {
	fd := rdesc.NewFuncDesc(g.fn, 1, g.sqlg, g.logger)
	if err := fd.Explain(); err != nil {
		return nil, g.fn.CreateError(err.Error())
	}
	if fd.BeanObj == nil {
		return nil, g.fn.CreateError("no struct bean found in funcion")
	}
	if fd.BeanObj != fd.Input.Bean {
		return nil, g.fn.CreateError("no struct bean found in funcion args")
	}
	bean, err := fd.BeanObj.GetBeanType()
	if err != nil {
		return nil, g.fn.CreateError(err.Error())
	}
	var sql = sqlgenerator.SQL{
		TableName: bean.TableName,
	}

	fd.SQL = g.sqlg.Truncate(&sql) // sql.CreateDelete() //   append(sqlParams, whereParams...)

	return fd, nil
}
